import { ActivatedRoute } from '@angular/router';
import { CacheService } from '@services/cache.service';
import { DataService } from '@services/data.service';
import { Component, OnInit, OnChanges, HostListener, Renderer2, ElementRef } from '@angular/core';
import { NavController, ModalController, ActionSheetController, NavParams, PopoverController } from '@ionic/angular';
import { StatusBar } from '@ionic-native/status-bar/ngx';

@Component({
    selector: 'home-popover',
    templateUrl: 'popover.html',
    styleUrls: ['popover.scss'],
})

export class PopoverPage implements OnInit, OnChanges {
    Page;             // 判断从哪个页面进来
    type;             // 搜索类型 0-模糊查询，1-搜集团，2-搜项目，3-搜功能点
    Vague;            // 模糊查询
    params;           // 默认显示列表接收的参数
    Search = [
        { name: '搜索', isShow: true },
        { name: '搜集团', isShow: true },
        { name: '搜项目', isShow: true },
        { name: '搜功能点', isShow: true },
        { name: '搜系统', isShow: true }
    ];
    companyId;        // 集团ID
    projectId;        // 项目ID
    theSearch;        // 搜索关键词
    noText;           // 输入框默认显示
    Groups = [];      // 获取集团列表
    Projects = [];    // 获取项目列表
    Functions = [];   // 获取功能点列表
    Systems = [];     // 获取系统列表

    canPock = false;  // 是否选择搜索类型
    isPermission = true;   // 是否显示集团 （权限）
    isProject = true;         // 是否显示项目 （页面）
    isSystem = false;         // 是否显示系统 （页面）
    Height
    constructor(
        public navCtrl: NavController,
        public modalCtrl: ModalController,
        public actionSheetCtrl: ActionSheetController,
        public dataService: DataService,
        public popoverCtrl: PopoverController,
        private navParams: NavParams,
        private cache: CacheService,
        private statusBar: StatusBar,
        private renderer: Renderer2,
        private el: ElementRef
    ) {
        this.type = this.navParams.get('type');
        this.params = this.navParams.get('params');
        this.companyId = this.params && this.params.companyId ?
            this.params.companyId : this.cache.currentCompany ? this.cache.currentCompany.companyId : '';
        this.projectId = this.navParams.get('projectId') ? this.navParams.get('projectId')
            : this.cache.currentProject ? this.cache.currentProject.projectId : '';
        this.Page = this.navParams.get('Page');
        const functionPoint = this.cache.functionPoint;
        // 如果是平台界面则无法搜索项目
        if (!this.Page) {
            this.isProject = false;
        }
        // 如果不是项目界面则无法搜索系统
        if (this.Page === 2) {
            this.isSystem = true;
        }
        // 如果是项目人员则无法搜索集团
        if (functionPoint.length === 1 || this.Page === 2) {
            this.isPermission = false;
        }
        this.noText = this.Search[this.type].name;
        if (this.type !== '0') {
            for (let i = 0; i < this.Search.length; i++) {
                if (i === parseInt(this.type, 10)) {
                    this.Search[i].isShow = true;
                } else {
                    this.Search[i].isShow = false;
                }
            }
        } else {
            this.Vague = true;
        }
        if (this.type === '1' || this.type === '2') {
            this.Vague = false;
            this.getAllCompany(false, null);
            this.getAllProject(this.companyId, false, null);
        }
    }

    ngOnInit() {
    }

    ngOnChanges() {
    }

    ionViewWillEnter() {
        this.statusBar.styleDefault();
        const h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        console.log('自适应高度', h);
        const scrollElm = this.el.nativeElement.querySelector('.home-content');
        this.renderer.setStyle(scrollElm, 'height', (h - 60) + 'px');
    }

    ionViewWillLeave() {
        this.statusBar.styleLightContent();
    }

    getItems(ev: any) {
        console.log(ev);
        const val = ev.target.value;
        if (this.type === '0') {
            if (val) {
                if (!this.canPock) {
                    for (let i = 0; i < this.Search.length; i++) {
                        this.Search[i].isShow = true;
                    }
                }
                this.Vague = false;
                this.getAllCompany(true, val);
                this.getFunctions(null, this.Page, true, val);
                this.getAllProject(this.companyId, true, val);
                this.getSystems(this.projectId, true, val);
            } else {
                if (!this.canPock) {
                    this.Vague = true;
                    this.noText = this.Search[0].name;
                    this.Groups = this.Projects = this.Functions = this.Systems = [];
                } else {
                    this.getAllCompany(false, null);
                    this.getFunctions(null, this.Page, false, null);
                    this.getAllProject(this.companyId, false, null);
                    this.getSystems(this.projectId, false, null);
                }
            }
        } else {
            this.Vague = false;
            if (val) {
                this.getAllCompany(true, val);
                this.getAllProject(this.companyId, true, val);
            } else {
                this.getAllCompany(false, null);
                this.getAllProject(this.companyId, false, null);
            }
        }
    }

    searchWich(i) {
        this.Vague = false;
        this.canPock = true;
        switch (i) {
            case 1:
                this.getAllCompany(false, null);
                break;
            case 2:
                this.getAllProject(this.companyId, false, null);
                break;
            case 3:
                this.getFunctions(null, this.Page, false, null);
                break;
            case 4:
                this.getSystems(this.projectId, false, null);
        }
        this.noText = this.Search[i].name;
        for (let k = 0; k < this.Search.length; k++) {
            if (k === parseInt(i, 10)) {
                this.Search[k].isShow = true;
            } else {
                this.Search[k].isShow = false;
            }
        }
    }

    // 获取所有的集团
    getAllCompany(search, val) {
        this.dataService.getCompanyInfo().subscribe(res => {
            this.Groups = res.data;
            if (search) {
                if (val && val.trim() !== '') {
                    this.Groups = this.Groups.filter((item) => {
                        return (item.companyName.indexOf(val) > -1);
                    });
                }
            }
        });
    }

    // 获取所有的项目
    getAllProject(companyId, search, val) {
        this.dataService.getProjectlistByCompanyId(companyId, null).subscribe(res => {
            this.Projects = res.data;
            if (search) {
                if (val && val.trim() !== '') {
                    this.Projects = this.Projects.filter((item) => {
                        return (item.projectName.indexOf(val) > -1);
                    });
                }
            }
        });
    }

    //  获取所有功能点
    getFunctions(systemID, Page, search, val) {
        this.dataService.getFunctions(systemID).subscribe(res => {
            let name = '';
            let type;
            const Functions = [];
            switch (Page) {
                case 0:
                    name = '平台层';
                    type = 8;
                    break;
                case 1:
                    name = '集团层';
                    type = 9;
                    break;
                case 2:
                    name = '项目层';
                    type = 10;
                    break;
            }
            for (let i = 0; i < res.data.length; i++) {
                if (res.data[i].menuName === name) {
                    for (let j = 0; j < res.data[i].children.length; j++) {
                        if (res.data[i].children[j].menuType !== type) {
                            Functions.push(res.data[i].children[j]);
                        }
                    }
                }
            }
            this.Functions = Functions;
            if (search) {
                if (val && val.trim() !== '') {
                    this.Functions = this.Functions.filter((item) => {
                        return (item.menuName.indexOf(val) > -1);
                    });
                }
            }
        });
    }

    // 获取所有系统
    getSystems(projectId, search, val) {
        this.dataService.getSystemList(projectId).subscribe(res => {
            this.Systems = res.data.datas;
            if (search) {
                if (val && val.trim() !== '') {
                    this.Systems = this.Systems.filter((item) => {
                        return (item.deviceSysName.indexOf(val) > -1);
                    });
                }
            }
        });
    }

    // 选择并跳转页面
    toDo(index, item) {
        const data = {
            type: index,
            item: item
        };
        console.log(data);
        this.popoverCtrl.dismiss(data);
    }

    // // 关闭选择弹窗
    closePopver() {
        this.popoverCtrl.dismiss();
    }

    // 返回上层搜索
    return() {
        this.Vague = true;
        this.theSearch = '';
        this.canPock = false;
        this.noText = this.Search[0].name;
        this.Groups = this.Projects = this.Functions = this.Systems = [];
    }
}
